import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style

NProgress.configure({ showSpinner: true })// NProgress Configuration

const whiteList = ['/login', '/authredirect']// no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  // 登陆状态
  if (store.getters.login_token && store.getters.login_mobile) { // determine if there has token
    /* has token , mobile*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      // 用户请求有权限的路由
      if (store.getters.api_routes.length === 0) { // 刷新则要重新拉取
        store.dispatch('getUserRoute').then(res => {
          // 拉取数据库的 routes
          if (store.getters.api_routes !== 'null') {
            router.addRoutes(store.getters.addRouters)
            // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          }
        })
      } else {
        // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        if (store.getters.api_routes !== 'null') {
          if (hasPermission(store.getters.api_routes, to.meta.roles)) {
            next()
          } else {
            next({ path: '/401', replace: true, query: { noGoBack: true }})
          }
          // 可删 ↑
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

// permissiom judge function
function hasPermission(api_route, metaRoles) {
  // if (api_route.indexOf('all') !== -1) return true // admin permission passed directly
  if (api_route === 'all') return true // admin permission passed directly
  if (!metaRoles) return true
  // 检测数组中是否有元素<==> X
  return api_route.some(role => metaRoles.indexOf(role) >= 0)
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
